package com.ruoyi.vote.app.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.websocket.WebSocketUsers;
import com.ruoyi.mall.domain.OrderInfo;
import com.ruoyi.mall.enums.OrderInfoEnum;
import com.ruoyi.mall.service.OrderInfoService;
import com.ruoyi.vote.admin.domain.VoteCertificateReceive;
import com.ruoyi.vote.admin.domain.VoteLike;
import com.ruoyi.vote.admin.service.IVoteActivityService;
import com.ruoyi.vote.admin.service.IVoteCertificateReceiveService;
import com.ruoyi.vote.admin.service.IVoteLikeService;
import com.ruoyi.vote.common.constants.ModelTypeConstants;
import com.ruoyi.vote.common.constants.PayConstants;
import com.ruoyi.vote.common.enums.CertificateTypeEnum;
import com.ruoyi.weixin.config.CommonConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * 订单处理
 * @author 立勤
 * @date 2023/07/24 17:44:05
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class PayService {

    private final OrderInfoService orderInfoService;
    private final IVoteCertificateReceiveService certificateReceiveService;
    private final IVoteLikeService voteLikeService;
    private final IVoteActivityService activityService;

    /**
     * 创建订单
     * @param order
     * @return
     */
    public Boolean orderSub(OrderInfo order){
        // id生成策略 :OrderNoCreate.randomOrderCode()
        order.setOrderNo(IdUtil.getSnowflake(0,0).nextIdStr());
        order.setCreateTime(LocalDateTime.now());
        order.setFreightPrice(BigDecimal.ZERO);
        order.setSalesPrice(order.getPaymentPrice());
        order.setUserId(String.valueOf(LoginHelper.getUserId()));
        order.setIsPay(CommonConstants.NO);
        order.setStatus(OrderInfoEnum.STATUS_0.getValue());
        log.info("--- 创建订单信息: {} ",order);
        return orderInfoService.save(order);//保存订单
    }


    /**
     * 订单回调处理
     * @param orderInfo
     * @return
     */
    public Boolean notifyOrder(OrderInfo orderInfo){
        orderInfo.setIsPay(CommonConstants.YES);
        orderInfo.setStatus(OrderInfoEnum.STATUS_1.getValue());
        orderInfoService.updateById(orderInfo);//更新订单

        switch (orderInfo.getModelType()){
            case ModelTypeConstants.CERTIFICATE:
                VoteCertificateReceive one = certificateReceiveService.getOne(new LambdaQueryWrapper<VoteCertificateReceive>()
                    .eq(VoteCertificateReceive::getOrderNo, orderInfo.getOrderNo())
                    .eq(VoteCertificateReceive::getIsPay, PayConstants.ERROR)
                    .eq(VoteCertificateReceive::getStatus, OrderInfoEnum.STATUS_0)
                    .eq(VoteCertificateReceive::getCType, CertificateTypeEnum.PAPER));
                if (ObjectUtil.isNotNull(one)){
                    one.setIsPay(PayConstants.SUCCESS);
                    one.setStatus(OrderInfoEnum.STATUS_1.getValue());
                    return certificateReceiveService.updateById(one);
                }
            break;
            case ModelTypeConstants.LIKE_VOTE:
                // 投票 成功
                VoteLike one1 = voteLikeService.getOne(new LambdaQueryWrapper<VoteLike>()
                    .eq(VoteLike::getOrderNo, orderInfo.getOrderNo())
                    .eq(VoteLike::getIsPay, PayConstants.ERROR)
                    .eq(VoteLike::getStatus, OrderInfoEnum.STATUS_0));
                if (ObjectUtil.isNotEmpty(one1)){
                    Boolean aBoolean = voteLikeService.likeUserVoting(String.valueOf(one1.getMId()), String.valueOf(one1.getAId()), one1.getLikeNumber(), 10);
                    if (aBoolean){
                        activityService.calculateRankingByaId(String.valueOf(one1.getMId()));
                        // 发送websocket信息
                        Session session = WebSocketUsers.getUsers().get(String.valueOf(one1.getMId()));
                        WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(R.ok()));
                    }
                    one1.setIsPay(PayConstants.SUCCESS);
                    one1.setStatus(OrderInfoEnum.STATUS_3.getValue());
                    return voteLikeService.updateById(one1);
                }
            break;
        }
        return true;
    }

}
